/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudexapps.manager.utilities;

import java.io.File;

import org.apache.log4j.Logger;

/**
 * @author Esko Luontola
 * @since 17.6.2008
 */
public class TempDirectory {

    private static Logger log = Logger.getLogger(TempDirectory.class);

    public static final String PREFIX = TempDirectory.class.getSimpleName() + ".";

    private File directory;
    
    
    public TempDirectory() {
    	
    }
    public TempDirectory(File directory) {
        this.directory = directory;
    }
    public File getDirectory() {
        return directory;
    }
    
    public void setDirectory(File directory) {
        this.directory = directory;
    }

    public void create() {
        if (directory == null) {
            directory = nonExistingTempDir();
        }
        if (directory.exists()) {
            throw new IllegalArgumentException("Already exists: " + directory);
        }
        if (!directory.mkdir()) {
            throw new RuntimeException("Unable to create directory: " + directory);
        }
    }

    private static File nonExistingTempDir() {
        int i = 0;
        File dir;
        do {
            i++;
            dir = new File(System.getProperty("java.io.tmpdir"), PREFIX + i);
        } while (dir.exists());
        return dir;
    }

    public void dispose() {
        deleteRecursively(directory);
    }

    public static void deleteRecursively(File file) {
        if (file.isDirectory()) {
            for (File contained : file.listFiles()) {
                deleteRecursively(contained);
            }
        }
        if (!file.delete()) {
            log.warn("Unable to delete file: " + file);
            anotherDeleteAttempt(file);
        }
    }
    public static boolean deleteAllFiles(File dir) {
        if(!dir.exists()) {
            return true;
        }
        boolean res = true;
        if(dir.isDirectory()) {
            File[] files = dir.listFiles();
            for(int i = 0; i < files.length; i++) {
                res &= deleteAllFiles(files[i]);
            }
        } else {
            res = dir.delete();
        }
        return res;
    }
    private static void anotherDeleteAttempt(File file) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean isDeleted = file.delete();
        
        if (!isDeleted) {
        	file.deleteOnExit();
        	if (!file.exists())
        		log.info("File was deleted on a second try: " + file);
        }
    }
}
